package com.base.hong.ui.base

import android.os.Bundle
import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.base.hong.ext.showToast
import com.base.hong.ui.MainActivity
import com.htt.base_library.base.BaseFragment
import com.htt.base_library.base.BaseVModel
import com.htt.base_library.constant.BaseConstant
import com.htt.base_library.manager.ActivityManager
import com.htt.base_library.util.ClassUtil
import com.base.hong.utils.SPUtils
import com.htt.base_library.util.startActivity

/**
 *
 * Created by hong on 2021/7/13 9:46.
 *
 */
abstract class BaseVMFragment<VM : BaseVModel, VB : ViewBinding> : BaseFragment<VB>() {

    lateinit var viewModel: VM

    override fun initView(view: View, savedInstanceState: Bundle?) {
        initViewModel()
        super.initView(view, savedInstanceState)
    }

    open fun initViewModel() {
        var classType = ClassUtil.getViewModel<VM>(this)
        val mActivity = activity
        if (classType != null && mActivity != null) {
            viewModel = ViewModelProvider(this).get(classType)
            lifecycle.addObserver(viewModel)
            registerUIChange()
        }
    }

    /**
     * 注册 UI 事件
     */
    private fun registerUIChange() {
        viewModel.ui.showDialog.observe(this) {
            showLoadingDialog(it ?: "")
        }
        viewModel.ui.dismissDialog.observe(this) {
            dismissLoadingDialog()
        }
        viewModel.ui.errorEvent.observe(this) {
            dismissLoadingDialog()
            when (it.code) {
                BaseConstant.HTTP_CODE_LOGOUT -> {
                    showToast("当前登录状态过期，请您重新登录!")
                    SPUtils.clean()
                    ActivityManager.finishAllActivity()
                    startActivity<MainActivity>()
                }
                else -> {
                    showError(it.msg, it.code)
                }
            }
        }
    }

    open fun showError(msg: String, code: Int) {
        showToast(msg)
    }
}